package com.banksoft.cps.controller.trans;

import com.banksoft.cps.bean.Company;
import com.banksoft.cps.bean.TransportCompany;
import com.banksoft.cps.bean.common.ServiceException;
import com.banksoft.cps.constants.WebConstant;
import com.banksoft.cps.controller.ControllerConstants;
import com.banksoft.cps.service.TransportCompanyService;
import com.banksoft.cps.util.CookieUtil;
import com.banksoft.cps.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by rongzhao.zhu on 2018/8/30.
 */
@Controller
@RequestMapping("/trans/")
public class TMainController extends ControllerConstants {

    @Autowired
    TransportCompanyService transportCompanyService;
    @RequestMapping(value = "loginOn", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String login(String account, String password, HttpServletRequest request, HttpServletResponse response){
        TransportCompany user = null;
        try{
            user =  transportCompanyService.login(account,password);
            CookieUtil.setLoginCookie(response,user,"");
        }catch (ServiceException e){
            return toExceptionString(e);
        }
        return toJSONString(createDataTip(user));
    }
    @RequestMapping(value = "logout", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        for(Cookie cookie :request.getCookies()){
            if(WebConstant.cookieToken.equals(cookie.getName())){
                transportCompanyService.logout(cookie.getValue());
            }
        }
        return toJSONString(SUCCESS);
    }
    @RequestMapping(value = "updatePassword", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String updatePassword(String oldPassword,String newPassword) throws IOException {
        TransportCompany company = (TransportCompany) UserContext.getUser();
        try{
            transportCompanyService.updatePassword(company.getId(),oldPassword,newPassword);
        }catch (ServiceException e){
            return toExceptionString(e);
        }
        return toJSONString(SUCCESS);
    }
}
